<!-- src/views/data/PluginDataManagement.vue -->
<template>
  <div class="plugin-data-management">
    <!-- 数据统计面板 -->
    <el-card class="statistic-card">
      <template #header>
        <div class="card-header">
          <span>数据统计</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-statistic title="总批次数" :value="getStatisticValue(statistics.totalBatches)" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="总记录数" :value="getStatisticValue(statistics.totalRecords)" />
        </el-col>
        <el-col :span="6">
          <el-tooltip content="今日插件向服务器发送数据的批次数。每一批次可能包含多个数据记录。注意：批次数量可能大于记录数量，这是因为部分批次可能处理失败或数据被过滤。" placement="top">
            <el-statistic title="今日批次" :value="getStatisticValue(statistics.todayBatches)" />
          </el-tooltip>
        </el-col>
        <el-col :span="6">
          <el-tooltip content="今日插件拦截并成功发送到服务器的数据记录总数。注意：记录数量可能小于批次数量，这是因为部分批次中的数据可能因验证失败或去重而被过滤。" placement="top">
            <el-statistic title="今日记录" :value="getStatisticValue(statistics.todayRecords)" />
          </el-tooltip>
        </el-col>
      </el-row>
      
      <el-divider />
      
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="sub-title">按状态统计</div>
          <el-table :data="getStatisticTableData(statistics.batchByStatus)" style="width: 100%" size="small">
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                {{ getBatchStatusText(scope.row.status) }}
              </template>
            </el-table-column>
            <el-table-column prop="count" label="数量" />
          </el-table>
        </el-col>
        <el-col :span="12">
          <div class="sub-title">按分类统计</div>
          <el-table :data="getStatisticTableData(statistics.dataByCategory)" style="width: 100%" size="small">
            <el-table-column prop="category" label="分类">
              <template #default="scope">
                {{ getCategoryText(scope.row.category) }}
              </template>
            </el-table-column>
            <el-table-column prop="count" label="数量" />
          </el-table>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 批次列表 -->
    <el-card class="batch-card">
      <template #header>
        <div class="card-header">
          <span>数据批次</span>
          <el-button type="primary" @click="refreshBatches">刷新</el-button>
        </div>
      </template>
      
      <el-form :inline="true" :model="batchFilter" class="batch-filter">
        <el-form-item label="状态">
          <el-select v-model="batchFilter.status" placeholder="请选择状态" class="form-item-width" clearable>
            <el-option label="处理中" value="processing" />
            <el-option label="已完成" value="completed" />
            <el-option label="失败" value="failed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchBatches">查询</el-button>
          <el-button @click="resetBatchFilter">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table 
        :data="batches" 
        v-loading="loading.batches"
        style="width: 100%"
        @selection-change="handleBatchSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="batchId" label="批次ID" />
        <el-table-column prop="dataType" label="数据类型">
          <template #default="scope">
            {{ getCategoryText(scope.row.dataType) }}
          </template>
        </el-table-column>
        <el-table-column prop="count" label="数据量" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag 
              :type="getBatchStatusType(scope.row.status)"
            >
              {{ getBatchStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="processedCount" label="已处理" />
        <el-table-column prop="failedCount" label="失败" />
        <el-table-column prop="processingTime" label="处理时间(ms)" />
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="viewBatchDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="batchPagination.currentPage"
          v-model:page-size="batchPagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="batchPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleBatchSizeChange"
          @current-change="handleBatchCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 数据记录列表 -->
    <el-card class="item-card">
      <template #header>
        <div class="card-header">
          <span>数据记录</span>
          <el-button type="primary" @click="refreshItems">刷新</el-button>
        </div>
      </template>
      
      <el-form :inline="true" :model="itemFilter" class="item-filter">
        <el-form-item label="数据类型">
          <el-select v-model="itemFilter.category" placeholder="请选择数据类型" class="form-item-width" clearable>
            <el-option label="银行流水" value="bank" />
            <el-option label="销售订单" value="sales_order" />
            <el-option label="采购订单" value="purchase_order" />
            <el-option label="发票" value="invoice" />
            <el-option label="进项发票" value="incoming_invoice" />
            <el-option label="销项发票" value="outgoing_invoice" />
            <el-option label="公告" value="announcement" />
            <el-option label="未知" value="unknown" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="itemFilter.status" placeholder="请选择状态" class="form-item-width" clearable>
            <el-option label="待处理" value="pending" />
            <el-option label="已处理" value="processed" />
            <el-option label="失败" value="failed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchItems">查询</el-button>
          <el-button @click="resetItemFilter">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table 
        :data="dataItems" 
        v-loading="loading.items"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="itemId" label="记录ID" />
        <el-table-column prop="batchId" label="批次ID" />
        <el-table-column prop="url" label="请求URL" :show-overflow-tooltip="true" />
        <el-table-column prop="method" label="方法" width="80" />
        <el-table-column prop="category" label="数据类型">
          <template #default="scope">
            {{ getCategoryText(scope.row.category) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag 
              :type="getItemStatusType(scope.row.status)"
            >
              {{ getItemStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewItemDetail(scope.row)">详情</el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="reprocessItem(scope.row.itemId)"
              :loading="scope.row.reprocessing"
            >
              重新处理
            </el-button>
            <el-button size="small" type="danger" @click="deleteItem(scope.row.itemId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="itemPagination.currentPage"
          v-model:page-size="itemPagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="itemPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleItemSizeChange"
          @current-change="handleItemCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 数据详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      :title="detailDialog.title"
      width="80%"
      destroy-on-close
    >
      <el-tabs v-model="detailDialog.activeTab">
        <el-tab-pane label="基本信息" name="basic">
          <el-descriptions :column="2" border>
            <!-- 批次详情 -->
            <template v-if="detailDialog.dataType === 'batch'">
              <el-descriptions-item label="批次ID">{{ (detailDialog.data as PluginDataBatch)?.batchId }}</el-descriptions-item>
              <el-descriptions-item label="数据类型">{{ getCategoryText((detailDialog.data as PluginDataBatch)?.dataType) }}</el-descriptions-item>
              <el-descriptions-item label="数据量">{{ (detailDialog.data as PluginDataBatch)?.count }}</el-descriptions-item>
              <el-descriptions-item label="状态">{{ getBatchStatusText((detailDialog.data as PluginDataBatch)?.status) }}</el-descriptions-item>
              <el-descriptions-item label="已处理">{{ (detailDialog.data as PluginDataBatch)?.processedCount }}</el-descriptions-item>
              <el-descriptions-item label="失败">{{ (detailDialog.data as PluginDataBatch)?.failedCount }}</el-descriptions-item>
              <el-descriptions-item label="处理时间(ms)">{{ (detailDialog.data as PluginDataBatch)?.processingTime }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ formatDateTime((detailDialog.data as PluginDataBatch)?.createdAt) }}</el-descriptions-item>
              <el-descriptions-item label="更新时间">{{ formatDateTime((detailDialog.data as PluginDataBatch)?.updatedAt) }}</el-descriptions-item>
              <el-descriptions-item label="完成时间">{{ formatDateTime((detailDialog.data as PluginDataBatch)?.completedAt) }}</el-descriptions-item>
              <el-descriptions-item label="错误信息" :span="2">
                <el-text v-if="(detailDialog.data as PluginDataBatch)?.errorMessage" type="danger">
                  {{ (detailDialog.data as PluginDataBatch)?.errorMessage }}
                </el-text>
                <el-text v-else>无</el-text>
              </el-descriptions-item>
            </template>
            
            <!-- 数据项详情 -->
            <template v-else>
              <el-descriptions-item label="记录ID">{{ (detailDialog.data as PluginDataItem)?.itemId }}</el-descriptions-item>
              <el-descriptions-item label="批次ID">{{ (detailDialog.data as PluginDataItem)?.batchId }}</el-descriptions-item>
              <el-descriptions-item label="请求URL" :span="2">{{ (detailDialog.data as PluginDataItem)?.url }}</el-descriptions-item>
              <el-descriptions-item label="HTTP方法">{{ (detailDialog.data as PluginDataItem)?.method }}</el-descriptions-item>
              <el-descriptions-item label="数据类型">{{ getCategoryText((detailDialog.data as PluginDataItem)?.category) }}</el-descriptions-item>
              <el-descriptions-item label="状态">{{ getItemStatusText((detailDialog.data as PluginDataItem)?.status) }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ formatDateTime((detailDialog.data as PluginDataItem)?.createdAt) }}</el-descriptions-item>
              <el-descriptions-item label="处理时间">{{ formatDateTime((detailDialog.data as PluginDataItem)?.processedAt) }}</el-descriptions-item>
              <el-descriptions-item label="更新时间">{{ formatDateTime((detailDialog.data as PluginDataItem)?.updatedAt) }}</el-descriptions-item>
              <el-descriptions-item label="错误信息" :span="2">
                <el-text v-if="(detailDialog.data as PluginDataItem)?.errorMessage" type="danger">
                  {{ (detailDialog.data as PluginDataItem)?.errorMessage }}
                </el-text>
                <el-text v-else>无</el-text>
              </el-descriptions-item>
            </template>
          </el-descriptions>
        </el-tab-pane>
        
        <el-tab-pane label="请求数据" name="request">
          <pre class="data-preview">{{ formatJson((detailDialog.data as PluginDataItem)?.requestData) }}</pre>
        </el-tab-pane>
        
        <el-tab-pane label="响应数据" name="response">
          <pre class="data-preview">{{ formatJson((detailDialog.data as PluginDataItem)?.responseData) }}</pre>
        </el-tab-pane>
        
        <el-tab-pane label="规则信息" name="rule">
          <pre class="data-preview">{{ formatJson((detailDialog.data as PluginDataItem)?.ruleInfo) }}</pre>
        </el-tab-pane>
      </el-tabs>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { usePluginData } from '@/composables/usePluginData'
import type { PluginDataBatch, PluginDataItem } from '@/api/pluginData'

// 使用composable
const {
  statistics,
  batches,
  dataItems,
  batchPagination,
  itemPagination,
  loading,
  fetchStatistics,
  fetchBatches,
  fetchDataItems,
  fetchDataItemDetail,
  reprocessItem,
  deleteItem
} = usePluginData()

// 过滤条件
const batchFilter = reactive({
  status: ''
})

const itemFilter = reactive({
  category: '',
  status: ''
})

// 详情对话框
const detailDialog = reactive({
  visible: false,
  title: '',
  activeTab: 'basic',
  dataType: 'batch', // 'batch' 或 'item'
  data: null as PluginDataBatch | PluginDataItem | null
})

// 批次状态显示
const getBatchStatusType = (status: string) => {
  switch (status) {
    case 'processing': return 'warning'
    case 'completed': return 'success'
    case 'failed': return 'danger'
    default: return 'info'
  }
}

const getBatchStatusText = (status: string) => {
  switch (status) {
    case 'processing': return '处理中'
    case 'completed': return '已完成'
    case 'failed': return '失败'
    default: return status
  }
}

// 数据项状态显示
const getItemStatusType = (status: string) => {
  switch (status) {
    case 'pending': return 'warning'
    case 'processed': return 'success'
    case 'failed': return 'danger'
    default: return 'info'
  }
}

const getItemStatusText = (status: string) => {
  switch (status) {
    case 'pending': return '待处理'
    case 'processed': return '已处理'
    case 'failed': return '失败'
    default: return status
  }
}

// 数据分类显示
const getCategoryText = (category: string) => {
  const categoryMap: Record<string, string> = {
    'bank': '银行流水',
    'sales_order': '销售订单',
    'purchase_order': '采购订单',
    'invoice': '发票',
    'incoming_invoice': '进项发票',
    'outgoing_invoice': '销项发票',
    'announcement': '公告',
    'unknown': '未知',
    'order': '订单',
    'other': '其他'
  }
  return categoryMap[category] || category
}

// 获取统计数据的值，处理可能的JSON对象显示问题
const getStatisticValue = (value: any): number => {
  // 如果是数字，直接返回
  if (typeof value === 'number') {
    return value;
  }
  // 如果是对象或数组，尝试提取数值
  if (typeof value === 'object' && value !== null) {
    if (Array.isArray(value)) {
      // 如果是数组，返回数组长度
      return value.length;
    } else if (typeof value === 'object') {
      // 如果是对象，尝试获取count或其他数值属性
      if ('count' in value && typeof value.count === 'number') {
        return value.count;
      } else if ('total' in value && typeof value.total === 'number') {
        return value.total;
      }
      // 如果无法提取数值，返回0
      return 0;
    }
  }
  // 其他情况返回0
  return 0;
};

// 获取统计数据表格的数据，处理可能的JSON对象显示问题
const getStatisticTableData = (data: any): any[] => {
  // 如果是数组，直接返回
  if (Array.isArray(data)) {
    return data;
  }
  // 如果是对象，尝试转换为数组
  if (typeof data === 'object' && data !== null) {
    // 如果对象有entries或其他可迭代属性
    return [];
  }
  // 其他情况返回空数组
  return [];
};

// 时间格式化
const formatDateTime = (dateString: string | undefined) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

// JSON格式化
const formatJson = (data: any) => {
  if (!data) return '无数据'
  try {
    return JSON.stringify(data, null, 2)
  } catch (error) {
    return String(data)
  }
}

// 批次相关操作
const refreshBatches = () => {
  fetchBatches()
}

const searchBatches = () => {
  fetchBatches({
    page: 1,
    status: batchFilter.status
  })
}

const resetBatchFilter = () => {
  batchFilter.status = ''
  fetchBatches({ page: 1 })
}

const handleBatchSizeChange = (val: number) => {
  batchPagination.pageSize = val
  fetchBatches({ pageSize: val })
}

const handleBatchCurrentChange = (val: number) => {
  batchPagination.currentPage = val
  fetchBatches({ page: val })
}

const handleBatchSelectionChange = (val: PluginDataBatch[]) => {
  // 批次选择处理
}

// 数据项相关操作
const refreshItems = () => {
  fetchDataItems()
}

const searchItems = () => {
  fetchDataItems({
    page: 1,
    category: itemFilter.category,
    status: itemFilter.status
  })
}

const resetItemFilter = () => {
  itemFilter.category = ''
  itemFilter.status = ''
  fetchDataItems({ page: 1 })
}

const handleItemSizeChange = (val: number) => {
  itemPagination.pageSize = val
  fetchDataItems({ pageSize: val })
}

const handleItemCurrentChange = (val: number) => {
  itemPagination.currentPage = val
  fetchDataItems({ page: val })
}

// 查看详情
const viewBatchDetail = (row: PluginDataBatch) => {
  detailDialog.title = '批次详情'
  detailDialog.data = row
  detailDialog.dataType = 'batch'
  detailDialog.activeTab = 'basic'
  detailDialog.visible = true
}

const viewItemDetail = async (row: PluginDataItem) => {
  const detail = await fetchDataItemDetail(row.itemId)
  if (detail) {
    detailDialog.title = '数据记录详情'
    detailDialog.data = detail
    detailDialog.dataType = 'item'
    detailDialog.activeTab = 'basic'
    detailDialog.visible = true
  }
}

// 重新处理数据项
const reprocessItemHandler = async (itemId: string) => {
  const success = await reprocessItem(itemId)
  if (success) {
    // 刷新数据
    fetchDataItems()
  }
}

// 删除数据项
const deleteItemHandler = async (itemId: string) => {
  ElMessageBox.confirm('确定要删除这条数据记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const success = await deleteItem(itemId)
    if (success) {
      // 刷新数据
      fetchDataItems()
    }
  }).catch(() => {
    // 取消删除
  })
}

// 初始化数据
onMounted(() => {
  fetchStatistics()
  fetchBatches()
  fetchDataItems()
})
</script>

<style scoped>
.plugin-data-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.statistic-card {
  margin-bottom: 20px;
}

.sub-title {
  font-weight: bold;
  margin-bottom: 10px;
}

.batch-filter,
.item-filter {
  margin-bottom: 20px;
}

.data-preview {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  max-height: 400px;
  overflow: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 分页容器居右对齐 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>